import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# 自作耶個翻譯小工具
import urllib.request as ur
import urllib.parse as up
import json

while True:
    word = input('輸入翻譯：')

    data = {
        'kw': word,
    }

    # 先將進行編譯(將data作為ＵＲＬ查詢字符串)
    data_n = up.urlencode(data)
    print(data_n)

    request = ur.Request(
        url='https://fanyi.baidu.com/sug',
        data=data_n.encode('utf-8'),  # 把ＵＲＬ編碼轉成字節
        headers={
            'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36'
        }
    )

    # 增加代碼見健碩性
    try:
        response = ur.urlopen(request).read()
        ret = json.loads(response)
        print(ret)
        keys = ret['data'][0]['k']
        value = ret['data'][0]['v']
        print(keys, ':', value)
    except:
        print(': 查無此相關結果，請重新輸入')


